package com.cg.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;

/**
 * @ClassName StrUtils
 * @Description TODO
 * @Author CG
 * @Date 2023/12/17 17:19
 **/
public class StrUtils {

    /**
     * 获取字符串拼音的第一个组成字母
     */
    public static String toFirstChar(String userName){
        String pinyinStr = "";
        //转换为单个字符
        char[] newChar = userName.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < newChar.length; i++) {
            if(newChar[i] > 128){
                try {
                    pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i],defaultFormat)[0].charAt(0);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else{
                pinyinStr += newChar[i];
            }
        }
        return pinyinStr;
    }
}
